package com.weilan.blog.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.weilan.blog.admin.entity.*;
import com.weilan.blog.admin.mapper.BlogMapper;
import com.weilan.blog.admin.service.*;
import com.weilan.blog.admin.utils.WebUtil;
import com.weilan.blog.admin.vo.BlogVO;
import com.weilan.blog.base.enums.ELevel;
import com.weilan.blog.base.enums.EOriginal;
import com.weilan.blog.base.enums.EStatus;
import com.weilan.blog.base.global.Constants;
import com.weilan.blog.base.holder.RequestHolder;
import com.weilan.blog.base.serviceImpl.SuperServiceImpl;
import com.weilan.blog.common.global.MessageConf;
import com.weilan.blog.common.global.SQLConf;
import com.weilan.blog.common.global.SysConf;
import com.weilan.blog.picture.feign.PictureFeignClient;
import com.weilan.blog.utils.ResultUtil;
import com.weilan.blog.utils.StringUtils;
import com.weilan.blog.utils.UpdateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @description:
 * @author: 孙 峰
 * @time: 2020/9/23 14:58
 */
@Service
public class BlogServiceImpl extends SuperServiceImpl<BlogMapper, Blog> implements BlogService {
    @Autowired
    private WebUtil webUtil;
    @Autowired
    private PictureFeignClient pictureFeignClient;

    @Autowired
    private BlogCategoryService blogCategoryService;

    @Autowired
    private BlogTagService blogTagService;

    @Autowired
    private SysParamsService sysParamsService;

    @Autowired
    private SysAdminService sysAdminService;



    @Override
    public List<Blog> setTagByBlogList(List<Blog> list) {
        return null;
    }

    @Override
    public List<Blog> setTagAndSortByBlogList(List<Blog> list) {
        return null;
    }

    @Override
    public List<Blog> setTagAndSortAndPictureByBlogList(List<Blog> list) {
        return null;
    }

    @Override
    public Blog setTagByBlog(Blog blog) {
        return null;
    }

    @Override
    public Blog setSortByBlog(Blog blog) {
        return null;
    }

    @Override
    public List<Blog> getBlogListByLevel(Integer level) {
        return null;
    }

    @Override
    public IPage<Blog> getBlogPageByLevel(Page<Blog> page, Integer level, Integer useSort) {
        return null;
    }

    @Override
    public Integer getBlogCount(Integer status) {
        return null;
    }

    @Override
    public List<Map<String, Object>> getBlogCountByTag() {
        return null;
    }

    @Override
    public List<Map<String, Object>> getBlogCountByBlogSort() {
        return null;
    }

    @Override
    public Map<String, Object> getBlogContributeCount() {
        return null;
    }



    @Override
    public List<Blog> getSameBlogByBlogUid(String blogUid) {
        return null;
    }

    @Override
    public List<Blog> getBlogListByTop(Integer top) {
        return null;
    }

    /**
     * 获取分页数据
     *
     * @param blogVO
     * @return
     */
    @Override
    public IPage<Blog> getPageList(BlogVO blogVO) {
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(blogVO.getKeyword()) && !StringUtils.isEmpty(blogVO.getKeyword().trim())) {
            queryWrapper.like(SQLConf.TITLE, blogVO.getKeyword().trim());
        }
        if (!StringUtils.isEmpty(blogVO.getTagUid())) {
            queryWrapper.like(SQLConf.TAG_UID, blogVO.getTagUid());
        }
        if (!StringUtils.isEmpty(blogVO.getBlogCategoryUid())) {
            queryWrapper.like(SQLConf.BLOG_SORT_UID, blogVO.getBlogCategoryUid());
        }
        if (!StringUtils.isEmpty(blogVO.getLevelKeyword())) {
            queryWrapper.eq(SQLConf.LEVEL, blogVO.getLevelKeyword());
        }
        if (!StringUtils.isEmpty(blogVO.getIsPublish())) {
            queryWrapper.eq(SQLConf.IS_PUBLISH, blogVO.getIsPublish());
        }
        if (!StringUtils.isEmpty(blogVO.getIsOriginal())) {
            queryWrapper.eq(SQLConf.IS_ORIGINAL, blogVO.getIsOriginal());
        }

        //分页
        Page<Blog> page = new Page<>();
        page.setCurrent(blogVO.getCurrentPage());
        page.setSize(blogVO.getPageSize());

        queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);

        // 是否启动排序字段
        if (blogVO.getUseSort() == 0) {
            // 未使用，默认按时间倒序
            queryWrapper.orderByDesc(SQLConf.CREATE_TIME);
        } else {
            // 使用，默认按sort值大小倒序
            queryWrapper.orderByDesc(SQLConf.SORT);
        }

        IPage<Blog> pageList = page(page, queryWrapper);
        List<Blog> list = pageList.getRecords();

        if (list.size() == 0) {
            return pageList;
        }

        final StringBuffer fileUids = new StringBuffer();
        List<String> sortUids = new ArrayList<>();
        List<String> tagUids = new ArrayList<>();

        list.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getFileUid())) {
                fileUids.append(item.getFileUid() + SysConf.FILE_SEGMENTATION);
            }
            if (StringUtils.isNotEmpty(item.getBlogCategoryUid())) {
                sortUids.add(item.getBlogCategoryUid());
            }
            if (StringUtils.isNotEmpty(item.getTagUid())) {
                List<String> tagUidsTemp = StringUtils.changeStringToString(item.getTagUid(), SysConf.FILE_SEGMENTATION);
                for (String itemTagUid : tagUidsTemp) {
                    tagUids.add(itemTagUid);
                }
            }
        });
        String pictureList = null;
        if (fileUids != null) {
            pictureList = this.pictureFeignClient.getPicture(fileUids.toString(), SysConf.FILE_SEGMENTATION);
        }

        List<Map<String, Object>> picList = webUtil.getPictureMap(pictureList);
        Collection<BlogCategory> sortList = new ArrayList<>();
        Collection<BlogTag> tagList = new ArrayList<>();

        if (sortUids.size() > 0) {
            sortList = blogCategoryService.listByIds(sortUids);
        }
        if (tagUids.size() > 0) {
            tagList = blogTagService.listByIds(tagUids);
        }


        Map<String, BlogCategory> sortMap = new HashMap<>();
        Map<String, BlogTag> tagMap = new HashMap<>();
        Map<String, String> pictureMap = new HashMap<>();

        sortList.forEach(item -> {
            sortMap.put(item.getUid(), item);
        });

        tagList.forEach(item -> {
            tagMap.put(item.getUid(), item);
        });

        picList.forEach(item -> {
            pictureMap.put(item.get(SQLConf.UID).toString(), item.get(SQLConf.URL).toString());
        });


        for (Blog item : list) {

            //设置分类
            if (StringUtils.isNotEmpty(item.getBlogCategoryUid())) {
                item.setBlogCategory(sortMap.get(item.getBlogCategoryUid()));
            }

            //获取标签
            if (StringUtils.isNotEmpty(item.getTagUid())) {
                List<String> tagUidsTemp = StringUtils.changeStringToString(item.getTagUid(), SysConf.FILE_SEGMENTATION);
                List<BlogTag> tagListTemp = new ArrayList<BlogTag>();

                tagUidsTemp.forEach(tag -> {
                    tagListTemp.add(tagMap.get(tag));
                });
                item.setBlogTagList(tagListTemp);
            }

            //获取图片
            if (StringUtils.isNotEmpty(item.getFileUid())) {
                List<String> pictureUidsTemp = StringUtils.changeStringToString(item.getFileUid(), SysConf.FILE_SEGMENTATION);
                List<String> pictureListTemp = new ArrayList<>();

                pictureUidsTemp.forEach(picture -> {
                    pictureListTemp.add(pictureMap.get(picture));
                });
                item.setPhotoList(pictureListTemp);
            }
        }
        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public String addBlog(BlogVO blogVO) {
        HttpServletRequest request = RequestHolder.getRequest();
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConf.LEVEL, blogVO.getLevel());
        queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);
        Integer count = count(queryWrapper);
        // 判断插入博客的时候，会不会超过预期设置
        String addVerdictResult = addVerdict(count + 1, blogVO.getLevel());
        // 判断是否能够添加推荐
        if (StringUtils.isNotBlank(addVerdictResult)) {
            return addVerdictResult;
        }
        Blog blog = new Blog();
        //如果是原创，作者为用户的昵称
        String projectName = sysParamsService.getSysParamsValueByKey(SysConf.PROJECT_NAME_);
        if (EOriginal.ORIGINAL.equals(blogVO.getIsOriginal())) {
            SysAdmin admin = sysAdminService.getById(request.getAttribute(SysConf.ADMIN_UID).toString());
            if (admin != null) {
                blog.setAuthor(admin.getNickName());
                blog.setAdminUid(admin.getUid());
            }
            blog.setArticlesPart(projectName);
        } else {
            blog.setAuthor(blogVO.getAuthor());
            blog.setArticlesPart(blogVO.getArticlesPart());
        }
        blog.setTitle(blogVO.getTitle());
        blog.setSummary(blogVO.getSummary());
        blog.setContent(blogVO.getContent());
        blog.setTagUid(blogVO.getTagUid());
        blog.setBlogCategoryUid(blogVO.getBlogCategoryUid());
        blog.setFileUid(blogVO.getFileUid());
        blog.setLevel(blogVO.getLevel());
        blog.setIsOriginal(blogVO.getIsOriginal());
        blog.setIsPublish(blogVO.getIsPublish());
        blog.setStatus(EStatus.ENABLE);
        blog.setOpenComment(blogVO.getOpenComment());
        Boolean isSave = save(blog);

        //保存成功后，需要发送消息到solr 和 redis
        //updateSolrAndRedis(isSave, blog);
        return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS);
    }

    /**
     * 添加时校验
     *
     * @param count
     * @param level
     * @return
     */
    private String addVerdict(Integer count, Integer level) {

        //添加的时候进行判断
        // todo  需要对推荐等级验证
        switch (level) {
            case ELevel.FIRST: {
                Long blogFirstCount = 10L;// Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.BLOG_FIRST_COUNT));
                if (count > blogFirstCount) {
                    return ResultUtil.errorWithMessage("一级推荐不能超过" + blogFirstCount + "个");
                }
            }
            break;

            case ELevel.SECOND: {
                Long blogSecondCount = 10L;// Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.BLOG_SECOND_COUNT));
                if (count > blogSecondCount) {
                    return ResultUtil.errorWithMessage("二级推荐不能超过" + blogSecondCount + "个");
                }
            }
            break;

            case ELevel.THIRD: {
                Long blogThirdCount = 10L;// Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.BLOG_THIRD_COUNT));
                if (count > blogThirdCount) {
                    return ResultUtil.errorWithMessage("三级推荐不能超过" + blogThirdCount + "个");
                }
            }
            break;

            case ELevel.FOURTH: {
                Long blogFourthCount = 10L;//  Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.BLOG_FOURTH_COUNT));
                if (count > blogFourthCount) {
                    return ResultUtil.errorWithMessage("四级推荐不能超过" + blogFourthCount + "个");
                }
            }
            break;
            default: {

            }
        }
        return null;
    }

    /**
     * 博客编辑的思路
     * 1、
     *
     * @param blogVO
     * @return
     */
    @Override
    public String editBlog(BlogVO blogVO) {
        HttpServletRequest request = RequestHolder.getRequest();
        Blog blog = getById(blogVO.getUid());
        UpdateUtil.copyNullProperties(blogVO, blog);
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConf.LEVEL, blogVO.getLevel());
        queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);
        Integer count = count(queryWrapper);
        if (blog != null) {
            //传递过来的和数据库中的不同，代表用户已经修改过等级了，那么需要将count数加1
            if (!blog.getLevel().equals(blogVO.getLevel())) {
                count += 1;
            }
        }
        //
        String addVerdictResult = addVerdict(count, blogVO.getLevel());
        //添加的时候进行判断
        if (StringUtils.isNotBlank(addVerdictResult)) {
            return addVerdictResult;
        }
        //如果是原创，作者为用户的昵称
        SysAdmin sysAdmin = sysAdminService.getById(request.getAttribute(SysConf.ADMIN_UID).toString());
        blog.setAdminUid(sysAdmin.getUid());
        if (EOriginal.ORIGINAL.equals(blogVO.getIsOriginal())) {
            blog.setAuthor(sysAdmin.getNickName());
            String projectName = sysParamsService.getSysParamsValueByKey(SysConf.PROJECT_NAME_);
            blog.setArticlesPart(projectName);
        } else {
            blog.setAuthor(blogVO.getAuthor());
            blog.setArticlesPart(blogVO.getArticlesPart());
        }
        blog.setUpdateTime(LocalDateTime.now());
        blog.updateById();
        // 发消息到solr和redis
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public String editBatch(List<BlogVO> blogVOList) {
        return null;
    }

    @Override
    public String deleteBlog(BlogVO blogVO) {
        Blog blog = getById(blogVO.getUid());
        blog.setStatus(EStatus.DISABLED);
        Boolean save = blog.updateById();
        //保存成功后，需要发送消息到solr 和 redis, 同时从专题管理Item中移除该博客
        if (save) {
            Map<String, Object> map = new HashMap<>();
            map.put(SysConf.COMMAND, SysConf.DELETE);
            map.put(SysConf.BLOG_UID, blog.getUid());
            map.put(SysConf.LEVEL, blog.getLevel());
            map.put(SysConf.CREATE_TIME, blog.getCreateTime());
            //发送到RabbitMq
            // rabbitTemplate.convertAndSend(SysConf.EXCHANGE_DIRECT, SysConf.MOGU_BLOG, map);
            // 移除所有包含该博客的专题Item
            List<String> blogUidList = new ArrayList<>(Constants.NUM_ONE);
            blogUidList.add(blogVO.getUid());
            // subjectItemService.deleteBatchSubjectItemByBlogUid(blogUidList);
        }
        return ResultUtil.successWithMessage(MessageConf.DELETE_SUCCESS);
    }

    /**
     * 通过id删除博客
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public String deleteBatchBlog(Set<String> ids) {
        if (ids.isEmpty()) {
            return ResultUtil.errorWithMessage(MessageConf.PARAM_INCORRECT);
        }
        Collection<Blog> blogs = listByIds(ids);

        blogs.forEach(blog -> blog.setStatus(EStatus.DISABLED));

        boolean batch = updateBatchById(blogs);
        //保存成功后，需要发送消息到solr 和 redis
        if (batch) {
            //处理solr的逻辑
            // 处理redis逻辑
        }

        return ResultUtil.successWithMessage(MessageConf.DELETE_SUCCESS);
    }

    @Override
    public String deleteBatchBlog(List<BlogVO> blogVoList) {
        return null;
    }

    @Override
    public String uploadLocalBlog(List<MultipartFile> filedatas) throws IOException {
        return null;
    }

    @Override
    public void deleteRedisByBlogCategory() {

    }

    @Override
    public void deleteRedisByBlogTag() {

    }

    @Override
    public void deleteRedisByBlog() {

    }

    @Override
    public IPage<Blog> getBlogPageByLevel(Integer level, Long currentPage, Integer useSort) {
        return null;
    }

    @Override
    public IPage<Blog> getHotBlog() {
        return null;
    }

    @Override
    public IPage<Blog> getNewBlog(Long currentPage, Long pageSize) {
        return null;
    }

    @Override
    public IPage<Blog> getBlogBySearch(Long currentPage, Long pageSize) {
        return null;
    }

    @Override
    public IPage<Blog> getBlogByTime(Long currentPage, Long pageSize) {
        return null;
    }

    @Override
    public Integer getBlogPraiseCountByUid(String uid) {
        return null;
    }

    @Override
    public String praiseBlogByUid(String uid) {
        return null;
    }

    @Override
    public IPage<Blog> getSameBlogByTagUid(String tagUid) {
        return null;
    }

    @Override
    public IPage<Blog> getListByBlogSortUid(String blogSortUid, Long currentPage, Long pageSize) {
        return null;
    }

    @Override
    public Map<String, Object> getBlogByKeyword(String keywords, Long currentPage, Long pageSize) {
        return null;
    }

    @Override
    public IPage<Blog> searchBlogByTag(String tagUid, Long currentPage, Long pageSize) {
        return null;
    }

    @Override
    public IPage<Blog> searchBlogByBlogSort(String blogSortUid, Long currentPage, Long pageSize) {
        return null;
    }

    @Override
    public IPage<Blog> searchBlogByAuthor(String author, Long currentPage, Long pageSize) {
        return null;
    }

    @Override
    public String getBlogTimeSortList() {
        return null;
    }

    @Override
    public String getArticleByMonth(String monthDate) {
        return null;
    }


}
